package rockpaperscissor;

import java.io.*;
import java.net.*;
import java.util.Scanner;

public class Client {
    
    private static final int PORT = 8000;
    private static final String SERVER = "192.168.1.65";

    public static void main(String[] args) {
        String server = SERVER;
        int port = PORT;

        if (args.length >= 1) {
            server = args[0];
        }
        if (args.length >= 2) {
            port = Integer.parseInt(args[1]);
        }

        new Client(server, port);
    }

    public Client(String server, int port) {
        DataInputStream inputFromServer;
        DataOutputStream outputToServer;

        try {
            // create a socket to connect to the server
            Socket socket = new Socket(server, port);

            // create data input/output streams
            inputFromServer = new DataInputStream(socket.getInputStream());
            outputToServer = new DataOutputStream(socket.getOutputStream());

            // create Scanner object to read radius from the keyboard
            Scanner sc = new Scanner(System.in);
            System.out.println("Welcome to Rock Paper Scissor!");
            System.out.println("Waiting for game to start...");

            int playerNbr = inputFromServer.readInt();
            if(playerNbr ==7){
                System.out.println("the server is busy, please try again later");
            }
            else{
                System.out.println("You are player " + playerNbr);
                System.out.println("Game has started!\n 1.Rock\n 2.Paper\n 3.Scissor\n Enter a number: ");
            
                int choice = sc.nextInt();
                outputToServer.writeInt(choice);
                
                int result = inputFromServer.readInt();

                if (result == 0) {
                    System.out.println("It's a tie!");
                } else if (result == 1) {
                    System.out.println("Player 1 has won");
                } else if (result == 2) {
                    System.out.println("Player 2 has won");
                }
            }
            inputFromServer.close();
            outputToServer.close();
            socket.close();
        } catch (IOException e) {
            System.err.println(e);
        }

    }
}